package com.hk.controller;

import com.hk.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

//@RestController

/**
 * 注意返回的String要解析为html时，
 * 得使用@Controller，要不会返回为对象的形式，无法解析
 */
@Controller
@RequestMapping("myController")
@Slf4j
public class ShiroDemoController {

    //跳转登录页面
    @GetMapping("login")
    public String login(){
        return "login";
    }

    @GetMapping("userLogin1")
    public R userLogin(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);
            return R.ok("登录成功~~");
        } catch (Exception e) {
            return R.error("登录失败~~");
        }
    }


    //登录认证
    @GetMapping("userLogin")
    public String userLogin(String name, String pwd, HttpSession session){
        //1 获取 Subject 对象
        Subject subject = SecurityUtils.getSubject();
        //2 封装请求数据到 token 对象中
        AuthenticationToken token = new UsernamePasswordToken(name,pwd);
        //3 调用 login 方法进行登录认证
        try {
            subject.login(token);
            session.setAttribute("user",token.getPrincipal().toString());
            return "main";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("登录失败");
            return "登录失败";
        }
    }






//    @GetMapping("shiroDemo")
//    public R shiroDemo() {
//    public static void main(String[] args) {
        //1.初始化获取ecurityManager
//        IniSecurityManagerFactory factory = new
//                IniSecurityManagerFactory("classpath:shiro666.ini");
//        SecurityManager securityManager = factory.getInstance();
//        SecurityUtils.setSecurityManager(securityManager);
//
//        //2.获取Subject对象
//        Subject subject = SecurityUtils.getSubject();
//
//        //3.创建token对象
//        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "z3");
//
//        //4.完成登录
//        subject.login(token);
//        log.info("登录成功~~~");
//        System.out.println("登录成功~~~");
//
//        boolean result = subject.hasRole("role6");
//        System.out.println("是否拥有些权限：" + result);
//        return R.ok();
//    }


}
